package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/sms")
    public R sendSMS(String phone, HttpSession session){
        System.out.println("收到请求");
        //1.生成短信验证
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        System.out.println("验证码:"+code);

        //2.保存验证码
        session.setAttribute(phone,code);

        //3.给手机号发送信息


        //4.返回结果
        return R.success(code);
    }

    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map, HttpSession session){

        //1.或手机号和验证码
        String phone = map.get("phone");

        String code = map.get("code");

        //2.验证登陆码
        String saveCode = (String)session.getAttribute(phone);

        if(saveCode != null && saveCode.equalsIgnoreCase(code)){

            //3.必须把用户的数据保存到数据库里面去

            //3.1先根据电话号码去数据库里面查询用户的信息
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);

            //3.2判定是否查询到用户
            if(user==null){
                //3.2.1如果有,表示该用户不是第一次登陆把用户对象保存到session作用域
                 user= new User();
                 user.setPhone(phone);
                 user.setName("菩提阁"+phone);
                 userService.save(user);
            }


            //3.2.2如果没有,即表示该用户是第一次登陆,把用户信息保存到数据库,也要保存到作用域
            session.setAttribute("user",user);
            return R.success("登陆成功");
        }


        return R.error("验证码错误");
    }
}
